package com.sky.aspect;

import com.sky.annotation.Autofill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFileAspect{
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.Autofill )")
    public void autoFillPointCut(){};

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint point){
        log.info("开始公共字段的填充"+point);
        // 获取当前拦截方法的类型
        MethodSignature signature = (MethodSignature)point.getSignature();
        Autofill autofill = signature.getMethod().getAnnotation(Autofill.class);
        OperationType operationType = autofill.value();
        // 获取被拦截的参数-- 实体对象
        Object[] args = point.getArgs();
        if(args == null || args.length == 0){
            return;
        }
        Object target = args[0];
        // 准备赋值的数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        // 根据不同类型，为对应的属性通过·反射·来赋值

        try {
            Method setCreateTime = target.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = target.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setCreateUser = target.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateUser = target.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            // 反射赋值

            if(operationType == OperationType.UPDATE){
                setUpdateTime.invoke(target,now);
                setUpdateUser.invoke(target,currentId);
            }else if(operationType == OperationType.INSERT){
                setCreateTime.invoke(target,now);
                setCreateUser.invoke(target,currentId);
                setUpdateTime.invoke(target,now);
                setUpdateUser.invoke(target,currentId);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    };
}
